package com.flyoil.petromp.ui.activity.activity_me;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cnpc.fyimageloader.utils.ImageTools;
import com.cnpc.fyimageloader.utils.ImageUtils;
import com.cnpc.fyimageloader.utils.PhotoUtil;
import com.cnpc.fyutils.SystemUtils;
import com.cnpc.fyutils.ToastUtils;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseActivity;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.entity.entity_me.UserPhoneEntity;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.HintConstants;
import com.flyoil.petromp.utils.MoccaPreferences;
import com.flyoil.petromp.utils.PermissionUtils;
import com.flyoil.petromp.utils.RequestBody_Util;
import com.flyoil.petromp.view.ClipImageView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 保存签名的界面
 */
public class SaveSignatureActivity extends BaseActivity {
    /**
     * sign_ec:电子签名 sign_photo：照片签名
     */
    private String sign_type = "";
    /** 签名图片ID*/
    /**
     * 显示类型
     */
    private String uriImage;
    private Bitmap bitmap;
    private ClipImageView clip_image_view;
    private int mMaxWidth;
    // 图片被旋转的角度
    private int mDegree;

    /**
     * 提示语，我要重写，立即使用
     */
    private TextView tv_prompt_text, tv_cancle, tv_confirm;


    @Override
    protected int getContentViewResId() {
        return R.layout.activity_save_signature;
    }

    @Override
    protected void initConfigs() {
        httpModel = new HttpModel();
        if (getIntent().hasExtra("sign_type")) {
            sign_type = getIntent().getStringExtra("sign_type");
        }
        uriImage = getIntent().getStringExtra("ecsignimage");


    }

    @Override
    protected void initViews() {
        httpModel = new HttpModel();
        clip_image_view = $(R.id.clip_image_view);
        tv_prompt_text = $(R.id.tv_prompt_text);
        tv_cancle = $(R.id.tv_save_signature_cancle);
        tv_confirm = $(R.id.tv_save_signature_confirm);
        setTextTitleName("裁切签名");
        setImgLiftResid(R.mipmap.title_back);
        setImgLiftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetBackActivity();
            }
        });
        initSize();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            resetBackActivity();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void initSize() {
        clip_image_view.setAspect(5, 2);
        clip_image_view.setMaxOutputWidth(mMaxWidth);
        clip_image_view.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initEvents() {
        tv_cancle.setOnClickListener(onClickListener);
        tv_confirm.setOnClickListener(onClickListener);
        initBitmap();
    }

    /**
     * 将设置签名界面的传递过来的图片在界面上展示
     */
    private void initBitmap() {
        Dialog_util.start_NetworkRequests_diolog(mContext);
        ImageUtils.compressWidthImage(this, uriImage,
                SystemUtils.getScreenWidth(mContext)
        )
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<byte[]>() {
                    @Override
                    public void onCompleted() {
                        Dialog_util.close_NetworkRequests_diolog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Dialog_util.close_NetworkRequests_diolog();
                        Toast.makeText(mContext, "签名图片错误，请重新签名！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(byte[] bytes) {
                        bitmap = ImageTools.byteToBitmap(bytes);
                        Dialog_util.close_NetworkRequests_diolog();
                        if (bitmap != null) {
                            clip_image_view.setImageBitmap(bitmap);
                        }
                    }
                });
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_save_signature_cancle://重新书写
                    resetBackActivity();
                    break;
                case R.id.tv_save_signature_confirm://保存
                    PermissionUtils.requestPermission(mContext, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, new PermissionUtils.PermissionGrant() {

                        @Override
                        public void onPermissionGranted(int requestCode) {
                            sureOrSave();
                        }
                    });
                    break;
            }
        }
    };

    private void sureOrSave() {
        Bitmap bitmap = clip_image_view.clip();
        // TODO: 2017/2/20
        ImageUtils.saveSignatrueImage(this, bitmap, 100);
        uploadSignature(bitmap);
    }

    private void resetBackActivity() {
        startActivity(new Intent(mContext, SetSignatureActivity.class));
        finish();
    }

    /**
     * 将裁剪后的照片上传保存到服务器
     */
    private void uploadSignature(final Bitmap bitmap) {
        Dialog_util.start_NetworkRequests_diolog(mContext);
        File file_signature = PhotoUtil.compress_bitmap(bitmap, Environment.getExternalStorageDirectory() + "/image" + "usericonsignature.jpg");
        final Map<String, RequestBody> map = new HashMap<>();
        map.put(RequestBody_Util.parseImageMapKey("file", file_signature.getName()), RequestBody_Util.parseRequestBody_File(file_signature));
        httpModel.uploadSignature(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {

            @Override
            public void onSuccess(BaseEntity model) {
                ToastUtils.show_toast(model.getMessage());
                Dialog_util.close_NetworkRequests_diolog();
                UserPhoneEntity entity = null;
                if (model instanceof UserPhoneEntity) {
                    entity = (UserPhoneEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    MoccaPreferences.user_signature.put(entity.getData().getUrl());
                    MoccaPreferences.signature_seted.put(true);
                    backFinish();
                }
            }

            @Override
            public void onFailure(String msg) {
            }
        });


    }

    /**
     * 计算两个手指之间的距离。
     *
     * @param event
     * @return 两个手指之间的距离
     */
    private double distanceBetweenFingers(MotionEvent event) {
        float disX = Math.abs(event.getX(0) - event.getX(1));
        float disY = Math.abs(event.getY(0) - event.getY(1));
        return Math.sqrt(disX * disX + disY * disY);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, new PermissionUtils.PermissionGrant() {
            @Override
            public void onPermissionGranted(int requestCode) {
                switch (requestCode) {
                    case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                        sureOrSave();
                        break;
                    default:
                        break;
                }
            }
        });
    }


}
